package com.tywj.buscustomerapp.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.internal.BottomNavigationItemView;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.broadcast.NetWorkStateReceiver;
import com.tywj.buscustomerapp.model.bean.CityBean;
import com.tywj.buscustomerapp.utils.LocationUtils;
import com.tywj.buscustomerapp.utils.PermissionsChecker;
import com.tywj.buscustomerapp.utils.PhoneUtils;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.adapter.ViewPagerAdapter;
import com.tywj.buscustomerapp.view.fragment.OutDoorFragment;
import com.tywj.buscustomerapp.view.fragment.SchoolTravelFragment;
import com.tywj.buscustomerapp.view.fragment.TourismFragment;
import com.tywj.buscustomerapp.view.fragment.newTravelFragment;
import com.tywj.buscustomerapp.view.myview.TaylorPopupWindow1;
import com.tywj.buscustomerapp.view.myview.TaylorViewPager;
import com.umeng.analytics.MobclickAgent;

import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;

/***
 * created by qiaokai
 * 2018.5.15
 */
public class MainActivity extends BaseActivity {

    private BottomNavigationView bottomNavigationView;
    private TaylorViewPager viewPager;
    private MenuItem menuItem;
    private ImageView headLeft;
    private DrawerLayout drawerLayout;
    private TextView headTitle;
    private TextView headCity;
    private RelativeLayout userLayout;
    private TextView userName;
    private TextView userPhone;
    private String user;
    private LinearLayout cs;
    private LinearLayout my_travel;
    private LinearLayout my_application_line;
    private LinearLayout activity_line;
    private LinearLayout my_ticket;
    private LinearLayout my_month_ticket;
    private LinearLayout more;
    private LinearLayout cd917;
    private String mapcity = null;
    private NetWorkStateReceiver netBroadcastReceiver;
    private PermissionsChecker mPermissionsChecker;
    private TaylorPopupWindow1 popupWindow;
    //权限集合
    static final String[] PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    private static final int PERMISSIONS_REQUEST_STORAGE = 1;
    private static final int INSTALL_PACKAGES_REQUESTCODE = 2;

    @Override
    protected int getContentId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initTheme() {
        super.initTheme();
        setTheme(R.style.AppTheme);
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        if (mPermissionsChecker == null){
            mPermissionsChecker = new PermissionsChecker(this);
        }        if (mPermissionsChecker == null){
            mPermissionsChecker = new PermissionsChecker(this);
        }
        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)){
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS,PERMISSIONS_REQUEST_STORAGE);
        }
        startActivity(new Intent(this,WelcomeActivity.class));
        initWidget();
        initClick1();
        //实例化IntentFilter对象
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        netBroadcastReceiver = NetWorkStateReceiver.getInstance();
        //注册广播接收
        registerReceiver(netBroadcastReceiver, filter);
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    private void initWidget() {
        bottomNavigationView = findViewById(R.id.navigation);
        viewPager = findViewById(R.id.viewpager);
        drawerLayout = findViewById(R.id.drawer);
        headLeft = findViewById(R.id.head_left);
        headTitle = findViewById(R.id.head_title);
        headCity = findViewById(R.id.head_right);
        userLayout = findViewById(R.id.drawer_user);
        userName = findViewById(R.id.user_name);
        userPhone = findViewById(R.id.user_phone);
        my_travel = findViewById(R.id.my_travel);
        cd917 = findViewById(R.id.cd917);
        more = findViewById(R.id.more);
        my_month_ticket = findViewById(R.id.my_mon_ticket);
        my_application_line = findViewById(R.id.my_application_line);
        my_ticket = findViewById(R.id.my_ticket);
        activity_line = findViewById(R.id.line_activity);
        cs = findViewById(R.id.cs);
        initBottomNav();
        CityBean city = SPUtils.getCity(getApplicationContext());
        if (city!=null && city.getCityId()!=null &&  !city.getCityId().equals("")){
            headCity.setText(city.getCityName());
        }else{
            initData1();
        }
        getUpdate();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            String mapCity1 = aMapLocation.getCity().replace("市","");
            if (mapCity1!=null && !mapCity1.equals("")){
                getCitys();
                mapcity = mapCity1;
            }else{
                CityBean cityBean = new CityBean();
                cityBean.setCityId("001");
                cityBean.setCityName("成都");
                SPUtils.rememberCity(getApplicationContext(),cityBean);
                headCity.setText(cityBean.getCityName());
//                TravelFragment.getInstance().loadData();
                newTravelFragment.getInstance().loadData(true);
            }

        }
    };

    private void getUpdate(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String msg = WebServicrUtils.getInstance().getUpdateApp();
                    String[] info = msg.split(",");
                    int version = PhoneUtils.getLocalVersion(getApplication());
                    if (info[0]!=null && version<Integer.valueOf(info[0])){
                        Log.i("update","需要更新"+msg);
                        Message message = Message.obtain();
                        message.what = 2222;
                        if (info[1]!=null && info[1].equals("强制更新")){
                            message.arg1=1;
                        }else{
                            message.arg1=0;
                        }
                        message.arg2=Integer.valueOf(info[0]);
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void getCitys() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String msg = WebServicrUtils.getInstance().getCityInWebService();
                    InputStream in_nocode = new ByteArrayInputStream(msg.getBytes("UTF-8"));
                    List<CityBean> list = WebServicrUtils.getInstance().getCitys(in_nocode);
                    if (list!=null && list.size()>0){
                        Message message = Message.obtain();
                        message.what = 2001;
                        message.obj = list;
                        handler.sendMessage(message);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==2001){
                List<CityBean> list = (List<CityBean>) msg.obj;
                if (list!=null && list.size()>0 && mapcity!=null){
                    for (int i = 0; i < list.size(); i++) {
                        if (mapcity.equals(list.get(i).getCityName())){
                            SPUtils.rememberCity(getApplicationContext(),list.get(i));
                            headCity.setText(list.get(i).getCityName());
//                            TravelFragment.getInstance().loadData();
                            newTravelFragment.getInstance().loadData(true);
                        }
                    }
                }
            }else if (msg.what==2222){
                showDialog("发现新版本","发现新版本，请更新",msg.arg1,msg.arg2);
            }
        }
    };


    private void updateApp(){
        AllenVersionChecker
                .getInstance()
                .downloadOnly(
                        UIData.create().setDownloadUrl(Config.UPDATEURL).setTitle("胖哒直通车").setContent("开始下载")
                )
                .setNotificationBuilder(
                        NotificationBuilder.create()
                                .setRingtone(true)
                                .setIcon(R.mipmap.ic_launcher)
                                .setContentTitle("胖哒直通车")
                                .setContentText("")
                )
                .setForceRedownload(true)
                .setShowDownloadingDialog(false)
                .excuteMission(MainActivity.this);
    }

    private void installApp(Context context, String path){
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            Intent install =new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.parse("file:/" + path), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }else{
            File apk = new File(path);
            Uri apkUri =
                    FileProvider.getUriForFile(context, getPackageName() + ".fileprovider", apk);
            Intent install2 =new Intent(Intent.ACTION_VIEW);
            install2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install2.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install2);
        }
    }

    private View getView(){
        return viewPager;
    }


    private void updateApp1(final Context context, int version,View view){
        String path = Environment.getExternalStorageDirectory().getAbsoluteFile()+"/com.tywj.buscustomerapp/";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        FileDownloader.setup(context);
        popupWindow = new TaylorPopupWindow1(context);
        MainActivity activity = (MainActivity) context;
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.showAtDropDownCenter(activity.getView());

        FileDownloader.getImpl().create(Config.UPDATEURL)
                .setPath(file.getPath()+"/胖哒直通车_"+version+".apk")
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        int pro = soFarBytes*100 / totalBytes;
                        if (popupWindow!=null && popupWindow.isShowing())
                            popupWindow.setProgress(pro);
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
//                        Log.i("DOWNLOAD_APP","完成:"+task.getPath());
                        installApp(context,task.getPath());
                        if (popupWindow!=null && popupWindow.isShowing())
                            popupWindow.dismiss();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
//                        Log.i("DOWNLOAD_APP_ERROR",e.getMessage());
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
//                        Log.i("DOWNLOAD_APP_WARN",task.getEtag());
                    }
                }).start();
    }


    private void initData1() {
        LocationUtils.getInstance().getLocationByLow(this,mLocationListener);
    }

    private void initClick1() {
        headLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user!=null && !user.equals("")){
                    drawerLayout.openDrawer(Gravity.LEFT);
                }else{
                    Intent loginIntent = new Intent(MainActivity.this,LoginActivity.class);
                    startActivityForResult(loginIntent,0);
                }
            }
        });

        headCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ChooseCityActivity.class);
                startActivityForResult(intent,0);
            }
        });

        userLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });

        cs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,CSActivity.class));
            }
        });

        my_travel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MyTravelActivity.class));
            }
        });
        my_application_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,ApplicationLineActivity.class));
            }
        });
        activity_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,ActCenterActivity.class));
            }
        });
        my_ticket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MyTicketActivity.class));
            }
        });
        more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MoreActivity.class));
            }
        });
        cd917.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,WebActivity.class);
                intent.putExtra("url","2");
                startActivity(intent);
            }
        });
        my_month_ticket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,MyMonthTicketActivity.class));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1002){
            CityBean city = (CityBean) data.getSerializableExtra("city");
            if (city!=null && !city.equals("")){
                headCity.setText(city.getCityName());
                SPUtils.rememberCity(getApplicationContext(),city);
//                TravelFragment.getInstance().loadData();
                newTravelFragment.getInstance().loadData(true);
            }
        }else if (resultCode==1003){
            // TODO: 2018/5/23 放用户数据
            drawerLayout.openDrawer(Gravity.LEFT);
            user = SPUtils.getUserPhone(getApplicationContext());
            userName.setText(user);
            userPhone.setText(user);
        }else if (requestCode==10012){
//            doDownloadUp();
        }

    }

    /***
     * 初始化底部导航栏
     */
    private void initBottomNav() {
        BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(newTravelFragment.getInstance());
        adapter.addFragment(OutDoorFragment.getInstance());
//        adapter.addFragment(TravelFragment.getInstance());
//        adapter.addFragment(TourismFragment.getInstance());
//        adapter.addFragment(SchoolTravelFragment.getInstance());
//        adapter.addFragment(AirTravelFragment.getInstance());
//        adapter.addFragment(TrainTravelFragment.getInstance());
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(4);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        bottomNavigationView.setItemIconTintList(null);
        /**
         * viewpager监听
         */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                if (bottomNavigationView.getMenu() != null) {
                    menuItem = bottomNavigationView.getMenu().getItem(position);
                    menuItem.setChecked(true);
                }
                switch (position){
                    case 0:
                        headTitle.setText(R.string.nav_travel);
                        break;
                    case 1:
                        headTitle.setText(R.string.nav_school);
//                        headTitle.setText("校园");
                        break;
//                    case 2:
//                        headTitle.setText(R.string.nav_air);
//                        break;
//                    case 3:
//                        headTitle.setText(R.string.nav_train);
//                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 底部导航栏变化监听
     */
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            resetToDefaultIcon();
            try {
                switch (item.getItemId()) {
                    case R.id.nav_home:
                        item.setIcon(R.mipmap.icon_home_bus_sel);
                        headTitle.setText(R.string.nav_travel);
                        viewPager.setCurrentItem(0);
                        return true;
                    case R.id.nav_status:
                        item.setIcon(R.mipmap.icon_home_travel_sel);
                        headTitle.setText("胖哒户外");
                        viewPager.setCurrentItem(1);
                        return true;
//                        item.setIcon(R.mipmap.icon_home_travel_sel);
//                        if (user!=null && !user.equals("")){
//                            Intent intent = new Intent(MainActivity.this,WebActivity.class);
//                            intent.putExtra("url","1");
//                            startActivity(intent);
//                        }else{
//                            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
//                            startActivity(intent);
//                        }
//                    case R.id.nav_baby:
//                        headTitle.setText(R.string.nav_air);
//                        viewPager.setCurrentItem(2);
//                        return true;
//                    case R.id.na+v_school:
//                        headTitle.setText(R.string.nav_train);
//                        viewPager.setCurrentItem(3);
//                        return true;
                }
                return true;
            }catch (Exception e){
                return false;
            }
        }

    };


    private void resetToDefaultIcon() {
        MenuItem home =  bottomNavigationView.getMenu().findItem(R.id.nav_home);
        home.setIcon(R.mipmap.icon_home_bus_nor);
        MenuItem travel =  bottomNavigationView.getMenu().findItem(R.id.nav_status);
        travel.setIcon(R.mipmap.icon_home_travel_nor);
    }

    /**
     * 适配底部导航栏样式
     */
    public static class BottomNavigationViewHelper {
        @SuppressLint("RestrictedApi")
        public static void disableShiftMode(BottomNavigationView view) {
            BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
            try {
                Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
                shiftingMode.setAccessible(true);
                shiftingMode.setBoolean(menuView, false);
                shiftingMode.setAccessible(false);
                for (int i = 0; i < menuView.getChildCount(); i++) {
                    BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
                    item.setShiftingMode(false);
                    item.setChecked(item.getItemData().isChecked());
                }
            } catch (NoSuchFieldException e) {
            } catch (IllegalAccessException e) {
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        user = SPUtils.getUserPhone(getApplicationContext());
        if (user!=null && !user.equals("")){
            userPhone.setText(user);
            userName.setText(user);
        }else{
            if (drawerLayout.isDrawerOpen(Gravity.LEFT))
                drawerLayout.closeDrawers();
        }
//        if (bottomNavigationView!=null && bottomNavigationView.getMenu()!=null){
//            menuItem = bottomNavigationView.getMenu().getItem(0);
//            menuItem.setChecked(true);
//            menuItem.setIcon(R.mipmap.icon_home_bus_sel);
//            MenuItem travel = bottomNavigationView.getMenu().getItem(1);
//            travel.setChecked(false);
//            travel.setIcon(R.mipmap.icon_home_travel_nor);
//        }

        MobclickAgent.onResume(this); //统计时长
//        setTheme(R.style.AppTheme);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(netBroadcastReceiver!=null) {
            unregisterReceiver(netBroadcastReceiver);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSIONS_REQUEST_STORAGE: {
                // 如果取消权限，则返回的值为0
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    ToastUtils.show("请开启定位权限");
                }
                break;
            }
            case INSTALL_PACKAGES_REQUESTCODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    installApk();
                } else {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    startActivityForResult(intent, 10012);
                }
                break;

        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.show("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void showDialog(final String title, final String msg,final int type,final int version){
        final AlertDialog build = new AlertDialog.Builder(MainActivity.this,R.style.AlertDialogStyle).create();
        //自定义布局
        View view = getLayoutInflater().inflate(R.layout.dialog_layout, null);
        build.setCanceledOnTouchOutside(false);
        build.setView(view, 0, 0, 0, 0);
        if (build!=null)
            build.show();
        //得到当前显示设备的宽度，单位是像素
        int width = getWindowManager().getDefaultDisplay().getWidth();
        //得到这个dialog界面的参数对象
        WindowManager.LayoutParams params = build.getWindow().getAttributes();
        //设置dialog的界面宽度
        params.width = width-(width/3);
        //设置dialog高度为包裹内容
        params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的重心
        params.gravity = Gravity.CENTER;
        build.getWindow().setAttributes(params);
        TextView titleTv = view.findViewById(R.id.message);
        TextView messageTv = view.findViewById(R.id.message1);
        titleTv.setText(title);
        messageTv.setText(msg);
        Button btn_sure = view.findViewById(R.id.yes);
        Button btn_cancel = view.findViewById(R.id.no);
        if (type==1){
            build.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    MainActivity.this.finish();
                }
            });
        }
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)){
                    ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS,PERMISSIONS_REQUEST_STORAGE);
                }
                updateApp1(MainActivity.this,version,v);
//                updateApp();
                if (type!=1){
                    build.dismiss();
                }
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (type==1){
                    MainActivity.this.finish();
                }else {
                    build.dismiss();
                }
            }
        });

    }



}
